using System.Collections.Generic;
using System.Reflection;
using Tickets.Model;
using Tickets.Model.Repositories;

namespace Tickets.Infrastructure.Repositories.Memory
{
	public class ProjectRepository : IProjectRepository
	{

		private static Dictionary<int, Project> instances = new Dictionary<int, Project>();

		#region IProjectRepository Members
		public Project GetById(int id)
		{
			if (instances.ContainsKey(id))
				return instances[id];

			return null;
		}

		public Project GetByCode(string projectCode)
		{
			foreach (KeyValuePair<int, Project> pair in instances)
				if (pair.Value.Code.Trim().ToLower() == projectCode.Trim().ToLower())
					return pair.Value;

			return null;
		}

		public Project GetByTicketId(int ticketId)
		{
			foreach (KeyValuePair<int, Project> pair in instances)
				foreach (Ticket ticket in pair.Value.GetTicketsSortedByCode())
					if (ticket.Id.Equals(ticketId))
						return pair.Value;

			return null;
		}

		public IList<Project> GetAll()
		{
			IList<Project> list = new List<Project>(instances.Values);

			return list;
		}

		public void Add(Project project)
		{
			if (project.Id == default(int))
				SetNewId(project);

			instances[project.Id] = project;
		}

		public void Save(Project project)
		{
			if (project.Id == default(int))
				SetNewId(project);

			instances[project.Id] = project;
		}

		public void Remove(Project project)
		{
			if (instances.ContainsKey(project.Id))
				instances.Remove(project.Id);
		}
		#endregion

		private static void SetNewId(Project project)
		{
			int newId = instances.Count + 1;
			project.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(project, newId);
		}

	}
}